﻿#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion

using System;
using System.Web.Mvc;
using Lokad.Monitoring.BusinessLogic;
using Lokad.Monitoring.Persistence.Entities;
using Lokad.Monitoring.Persistence.Repositories;
using Lokad.Monitoring.Rsm;

namespace Lokad.Monitoring.Controllers
{
    [AuthorizeOrRedirect]
    public class EndpointController : Controller
    {
        private readonly EndpointRepository _endpoints;
        private readonly ResponseRepository _responses;

        public EndpointController()
        {
            _endpoints = GlobalSetup.Container.Resolve<EndpointRepository>();
            _responses = GlobalSetup.Container.Resolve<ResponseRepository>();
        }

        public ActionResult Index()
        {
            return View(_endpoints.List());
        }

        public ActionResult Create()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Endpoint endpoint)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            _endpoints.Create(endpoint);
            return RedirectToAction("Index", _endpoints.List());
        }

        public ActionResult Edit(string id)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            return View(_endpoints.Edit(id));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string id, [Bind(Exclude = "Id")] Endpoint endpoint)
        {
            _endpoints.Edit(id, endpoint);
            return RedirectToAction("Index");
        }

        public ActionResult Delete(string id)
        {
            _endpoints.Delete(id);
            return RedirectToAction("Index");
        }

        public ActionResult Retrieve(string id)
        {
            var endpoint = _endpoints.Edit(id);

            var client = new RsmClient();
            var doc = new RsmDocument();
            try
            {
                doc = client.Open(endpoint.Url, endpoint.BasicAuth);

                // saving the response just retrieved
                _responses.Create(endpoint, doc);
            }
            catch (Exception ex)
            {
                ViewData["message"] = "Retrieval failed with: " + ex;
            }

            return View(doc);
        }

        public ActionResult Details(string id)
        {
            var endpoint = _endpoints.Edit(id);
            var latest = _responses.List(endpoint, DateTime.UtcNow.Subtract(new TimeSpan(7, 0, 0, 0))); // 7 days

            ViewData["endpointName"] = id;

            return View(latest);
        }
    }
}
